package thing

import (
	"github.com/gin-gonic/gin"
	logic2 "iot-base/auth/api/logic"
	"iot-base/auth/config"
	Log "iot-base/auth/logger"
	types2 "iot-base/auth/types"
	"iot-base/auth/utils"
	"iot-base/common/cache"
	"strings"
)

func DeviceList(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	var req types2.ReqDevice
	if err := c.ShouldBind(&req); err != nil {
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	isAuth := logic2.NewUserLogic().CheckThingAuth(uid, req.StationId)
	if isAuth == false {
		resp.Success(gin.H{})
	}
	deviceLogic := logic2.NewThingLogic()
	result, err := deviceLogic.ThingList(req.StationId)
	if err != nil {
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.DBError, "")
		return
	}
	resp.Success(result)
}

// GetStationThingInfo 获取设备信息.
func GetStationThingInfo(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	var req types2.ReqDevice
	if err := c.ShouldBind(&req); err != nil {
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	isAuth := logic2.NewUserLogic().CheckThingAuth(uid, req.StationId)
	if isAuth == false {
		resp.Success(gin.H{})
	}
	// 查询统计数据
	//logic2.NewStationLogic().HomeData(req.StationId)
	view, _ := cache.GetStationView(req.StationId)
	if view != nil {
		resp.Success(view)
		return
	}
	resp.Success(gin.H{})
}

func GetHomeThingData(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	var req types2.ReqGetHomeThingData
	if err := c.ShouldBind(&req); err != nil {
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	isAuth := logic2.NewUserLogic().CheckThingAuth(uid, req.StationId)
	if isAuth == false {
		resp.Success(gin.H{})
		return
	}
	Log.Log.Infof("[%s] json:=%v", requestId, config.ConfJson)
	stationLogic := logic2.NewStationLogic()
	modelIds := strings.Split(req.ModelIds, ",")
	result := utils.H{}
	for _, id := range modelIds {
		ret, err := stationLogic.HomeData(req.StationId, id, requestId.(string))
		Log.Log.Infof("[%s] stationLogic.HomeData:=%v , err:=%v", requestId, ret, err)
		if err != nil {
			continue
		}
		result[id] = ret
	}
	resp.Success(result)
}

func GetThingStatus(c *gin.Context) {
	requestId, _ := c.Get("RequestId")
	uid := c.GetInt64("uid")
	resp := types2.NewResult(c)
	var req types2.GetThingStatus
	if err := c.ShouldBind(&req); err != nil {
		Log.Log.Errorf("[%s] [%v] err:=%v", requestId, uid, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	modelIds := strings.Split(req.ModelIds, ",")
	status := gin.H{}
	for index := range modelIds {
		status[modelIds[index]] = logic2.GetThingRealTimeStatus(req.StationId, modelIds[index])
	}
	resp.Success(status)
}
